<?php


namespace app\common\services;


use app\common\model\AccessToken;
use think\Db;
use think\Exception;
use think\facade\Config;

class WechatService
{
    public $token;
    public $appid;
    public $secret;
    public $accessToken;

    public function __construct($token,$appid,$secret)
    {
        $this->token  = $token;
        $this->appid  = $appid;
        $this->secret = $secret;
        $this->getNowAccesstoken();
        $this->accessToken = $this->get_access_token();
    }


    // 获取access_token
    function get_access_token() {
        $model = Db::name("access_token");
        $map['token'] = $this->token;
        $info = $model->where($map)->find();
        if(!$info)
        {
            throw new Exception('获取不到数据库的token');
        }

        return $info['access_token'];
    }

    //获取新的access_token
    function getNowAccesstoken(){
        $nowtime = time();//现在时间
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->appid . '&secret=' . $this->secret;
        $ch1 = curl_init ();
        $timeout = 5;
        curl_setopt ( $ch1, CURLOPT_URL, $url );
        curl_setopt ( $ch1, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch1, CURLOPT_CONNECTTIMEOUT, $timeout );
        curl_setopt ( $ch1, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $ch1, CURLOPT_SSL_VERIFYHOST, false );
        $accesstxt = curl_exec ( $ch1 );
        curl_close ( $ch1 );
        $tempArr = json_decode ($accesstxt, true);
        if (isset($tempArr['access_token'])) {

            $model = new AccessToken();
            $map['token'] = $this->token;
            //保存新access_token到数据库，更新最后时间
            $data = array(
                'access_token'=>$tempArr ['access_token'],
                'lasttime'=>$nowtime
            );
            $info=$model->where($map)->find();
            if($info)
            {
                $model->allowField(true)->save($data,$map);
            }
            else
            {
                $data['token'] = $this->token;
                $model->allowField(true)->save($data);
            }
            return $tempArr['access_token'];
        }else{
            throw new Exception('公众号拿不到最新的token');
        }
    }

    //上传永久素材
    public function insertNews($topicInfo,$wechatInfo,$userInfo){
        $accessToken = $this->accessToken;
        $url = 'https://api.weixin.qq.com/cgi-bin/material/add_news?access_token='.$accessToken;

        //http://mmbiz.qpic.cn/mmbiz_gif/BvrdeyQmIomKgOp1bOib2HAgEy9HEwm0lk183CZZ9cIaOzia3aLY09K9CL6uachBols95lFAV2t11LXqPOSK0WQA/0
        //U91W61HNcPObL3RBmtvuVczaNc2h3k6bVVq5xDN_oSU

        //如果是分销版，就在下方面加入参数，
        //"content_source_url":"'.Config::get('params.php_server').'/h5",
        $content = '{
            "articles": [
                {
                    "thumb_media_id": "'.$wechatInfo['media_id'].'",
                    "author":"",
                    "title": "【立即查看】'.$topicInfo['title'].'",
                    
                    "content": "<p style=\"width: 400px;font-size:18px\">👇点击下方图片,开始测试👇</p><div style=\"background-image: url('.$wechatInfo['img_url'].');background-size:100%;background-position:center;width: 400px;height: 200px;margin: 15px auto;border: 1px solid #eeeeee;\"><p><strong><a class=\"weapp_text_link\" data-miniprogram-appid=\"'.Config::get('params.wxxcx_appid').'\" data-miniprogram-path=\"pages/detail/index?id='.$topicInfo['topic_id'].'\" data-miniprogram-nickname=\"'.$wechatInfo['program_name'].'\" href=\"\">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;  &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;  &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;     &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;  &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;  &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</a></strong></p></div><p style=\"width: 400px;font-size:18px\">👇👇👇点击下方开启属于您的视频号变现</p>",
                    "digest":"'.$topicInfo['title'].'",
                    "show_cover_pic": 0,
                    "need_open_comment":0,
                    "only_fans_can_comment":1
                }
            ]
        }';

        $res = httpByPost($url,$content,true);
        if(!empty($res['errcode']) && $res['errcode'] == 40001){throw new Exception('请更新token，获取不了标签');}
        if($res == null && empty($res['media_id'])){throw new Exception('生成永久素材失败');}

        return $res;
    }



    //获取用户标签，用于群发消息
    function getUserTag(){
        $accessToken = $this->accessToken;
        $url = 'https://api.weixin.qq.com/cgi-bin/tags/get?access_token='.$accessToken;
        $res= json_decode(curl_file_get_contents($url),true);
        if(!empty($res['tags'])){
            $res['tags'] = array_column($res['tags'],null,'name');
            return $res['tags'];
        }
        if($res == null){throw new Exception('获取不到用户标签');}
        if(!empty($res['errcode']) && $res['errcode'] == 40001){throw new Exception('请更新token，获取不了标签');}
    }


    //获取图文素材的链接
    function getNewsUrl($media_id){
        $content = '{
              "media_id":"'.$media_id.'"
            }';
        $accessToken = $this->accessToken;
        $url = 'https://api.weixin.qq.com/cgi-bin/material/get_material?access_token='.$accessToken;
        $res = httpByPost($url,$content,true);
        return $res;
    }

    //新增图片素材
    function insertPicture($real_path){
        $accessToken = $this->accessToken;
        $url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={$accessToken}&type=image";
        $ch1 = curl_init();
        $timeout = 5;
        $real_path=str_replace("\\", "/", $real_path);
        $path = new \CURLFile($real_path);
        $data = array('media'=>$path);
        curl_setopt($ch1, CURLOPT_URL, $url);
        curl_setopt($ch1, CURLOPT_POST, 1);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch1, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch1);
        return $result;
    }


    //群发里的新增图片素材
    function uploadPicture($real_path){
        $accessToken = $this->accessToken;
        $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$accessToken}&type=image";
        $ch1 = curl_init();
        $timeout = 5;
        $real_path=str_replace("\\", "/", $real_path);
        $path = new \CURLFile($real_path);
        $data = array('media'=>$path);
        curl_setopt($ch1, CURLOPT_URL, $url);
        curl_setopt($ch1, CURLOPT_POST, 1);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch1, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch1);
        return $result;
    }

    //群发里的上传图文素材
    function uploadNews($news){
        $accessToken = $this->accessToken;
        $url = 'https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token='.$accessToken;
        $res = httpByPost($url,$news,true);
        return $res;
    }

    //预览接口
    function preview($content){
        $accessToken = $this->accessToken;
        $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token='.$accessToken;
        $res = httpByPost($url,$content,true);
        return $res;
    }

    //群发接口
    public function sendAll($content){
        $accessToken = $this->accessToken;
        $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token='.$accessToken;
        $res = httpByPost($url,$content,true);
        return $res;
    }

    //获取群发状态
    public function massGet($content){
        $accessToken = $this->accessToken;
        $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/get?access_token='.$accessToken;
        $res = httpByPost($url,$content,true);
        return $res;
    }

    public function shortUrl($content){
        $accessToken = $this->accessToken;
        $url = 'https://api.weixin.qq.com/cgi-bin/shorturl?access_token='.$accessToken;
        $res = httpByPost($url,$content,true);
        return $res;
    }
}